package nl.nhl.idp.Components.Network;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import nl.nhl.idp.Components.Network.NetEvent.NetEventType;


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;

/**
 * This class handles the network communication
 * @author Mark van der Wal
 *
 */
public class NetworkController 
{
	// member variables
	private boolean mIsConnected;
	private int mServerPort;
	private String mServerAddress;
	
	private NetListener mNetListener;
	private NetworkWorker mNetworkThread;
	private NetworkSender mNetworkSender;
	
	private Socket mClientSocket;
	private DataOutputStream mOutput;
	private DataInputStream mInput;
	
	// outputQueue
	private BlockingQueue<byte[]> outQueue;
	
	/**
	 * constructor
	 */
	public NetworkController()
	{
		this("", 0);
	}
	
	/**
	 * Overloaded constructor
	 * @param address
	 * @param port
	 */
	public NetworkController(String address, int port)
	{
		mServerPort = port;
		mServerAddress = address;
		
		outQueue = new ArrayBlockingQueue<byte[]>(256);
	}
	
	/**
	 * Returns if we are connected
	 * @return true or false
	 */
	public boolean IsConnected() { return mIsConnected; }
	
	/**
	 * Set the ip adress
	 * @param ip
	 */
	public void SetIpAddress(String ip) { mServerAddress = ip; }
	
	/**
	 * Set the port
	 * @param port
	 */
	public void SetPort(int port) { mServerPort = port; }
	
	/**
	 * Set the network listener
	 * @param listener
	 */
	public void SetNetListener(NetListener listener) { mNetListener = listener;}
	
	/**
	 * Checks if we are connected to the internetz
	 * @return
	 */
    public boolean isInternetOn(Context context)
	{
		ConnectivityManager connec = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		
		if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)
		    ||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING)
		    ||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING)
		    ||(connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED))
		{
		    return true;
		}
		else if ((connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED)
		    || (connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED))
		{
		    return false;
		}
		
		    return false;
    }
	
	/**
	 * Try to connect to the specified server
	 */
	public void Connect()
	{
		mNetworkThread = new NetworkWorker();
		mNetworkThread.execute();
	}
	
	/**
	 * Disconnects from the server
	 * @throws IOException
	 */
	public void Disconnect() throws IOException
	{
		// interrupt the network thread
		mNetworkThread.cancel(false);
		mNetworkSender.cancel(false);
		mIsConnected = false;
		
		if(mClientSocket != null)
			mClientSocket.close();
		mClientSocket = null;
		
		outQueue.clear();
	}
	
	public void CheckQueue()
	{
		if(outQueue.size() > 10)
		{
			outQueue.clear();
		}
	}
	
	/**
	 * Sending data through network
	 * @param msg
	 */
	public void Send(byte[] data)
	{
		NetEvent event = new NetEvent();
		event.setEventID(NetEventType.TYPE_DISCON);
		
		try 
		{
			if(data != null)
			{    		
				outQueue.put(data);
			}
			else
			{
				if(mNetListener != null)
				{
					event.setMsg("Send: " + " no data to send (null)!!!");
					mNetListener.onNetEvent(event);
				}
			}
			
		} 
		catch(Exception e)
		{
			if(mNetListener != null)
			{
				event.setMsg("Could not send the message");
				mNetListener.onNetEvent(event);
			}
		}
	}
	
	/**
	 * Takes control of the sending of network messages
	 * @author Mark van der Wal
	 *
	 */
	private class NetworkSender extends AsyncTask<Void, NetEvent, Void>
	{	
		@Override
		protected Void doInBackground(Void... params) 
		{	
			// the message we use
    		NetEvent event = null;
			byte[] msg;
		
			try
			{
				while( (msg = outQueue.take()) != null)
				{
					mOutput.write(msg);
				}
			}
			catch(Exception e)
			{
	        	// send message
				event = new NetEvent();
				event.setEventID(NetEventType.TYPE_DISCON);
				event.setMsg("Disconnected from the vehicle");
	    		publishProgress(event);
			}
			
			return null;
		}
		
		
		@Override
		protected void onProgressUpdate( NetEvent... params)
		{
			// easier use of variable
			NetEvent event = params[0];
			
			// if we have a listener we pass the message to the listener
			if(mNetListener != null && event != null )
			{
				mNetListener.onNetEvent(event);
			}
		}
	}
	
	/**
	 * This AsyncTask inner class handles the IO of the network, it allows us to communicate with the android UI
	 * and in the same time has access to threading
	 * @author Mark van der Wal
	 *
	 */
	private class NetworkWorker extends AsyncTask<Void, NetEvent, Void>
	{	
		@Override
		protected Void doInBackground(Void... params) 
		{	
			// the message we use
    		NetEvent msg = null;
    		int index = 0;
    		
    		// byteBuffer
    		byte[] rawbuffer = new byte[128];
    		byte[] msgBuffer = new byte[7];
    		
        	try
        	{
            	try
            	{
		    		// trying to connect, this blocks for a moment
            		SocketAddress sa = new InetSocketAddress(mServerAddress, mServerPort);
            		mClientSocket = new Socket();
            		mClientSocket.setTcpNoDelay(true);
            		mClientSocket.connect(sa, 5000);
            	}
		        catch(Exception e)
		        {
		        	// send message
		        	msg = new NetEvent();
	    			msg.setEventID(NetEventType.TYPE_NOTIFI);
	    			msg.setMsg("Could not connect to " + mServerAddress + "!!");
		    		publishProgress(msg);
		    		
		    		return null;
		        }
            	
            	// we are connected if we get here
		    	mIsConnected = true;
	    		
	    		// get IO streams
	    		mOutput = new DataOutputStream(mClientSocket.getOutputStream());
	    		mOutput.flush();
	    		mInput = new DataInputStream(new BufferedInputStream(mClientSocket.getInputStream()));	
	    		
	    		// start sender thread
        		mNetworkSender = new NetworkSender();
        		mNetworkSender.execute();

	    		// send message the we are connected
	    		msg = new NetEvent();
    			msg.setEventID(NetEventType.TYPE_CON);
    			msg.setMsg("Connected to " + mClientSocket.getInetAddress().getHostAddress().toString());
				publishProgress(msg);

	    		// while this thread is running we will wait for input
	    		while(!isCancelled())
				{
	    			// create message
	    			msg = new NetEvent();
	    			msg.setEventID(NetEventType.TYPE_RECEIVE);
	    			
	    			//read the bytes
                    int read = mInput.read(rawbuffer);
                    
                    if(read != -1)
                    {
                    	while(index < read)
                    	{
                    		byte opcode = rawbuffer[index];
                    		
//                    		Log.d("Test", "opCode! " + (opcode & 0xFF));
                    		
                            // get the opcode
                            msg.setMsgID( opcode );

                            //### HACK !!! ### but it works!!!
                            if((opcode & 0xFF) == ProtocolOpcodes.V_SENSOR.Opcode())
                            {
//                            	for(int i =0; i < 7; i++)
//                            	{
//                            		Log.d("Test", "index: " + i + " value: " + rawbuffer[index + i + 1]);
//                            	}
                             	msgBuffer[0] = rawbuffer[index + 1];
                             	msgBuffer[1] = rawbuffer[index + 2];
                             	msgBuffer[2] = rawbuffer[index + 3];
                             	msgBuffer[3] = rawbuffer[index + 4];
                             	msgBuffer[4] = rawbuffer[index + 5];
                             	msgBuffer[5] = rawbuffer[index + 6];
                             	msgBuffer[6] = rawbuffer[index + 7];
                             	
                             	index += 8;
                            }
                            else if((opcode & 0xFF) == ProtocolOpcodes.V_MAZE_SENSOR.Opcode())
                            {
                            	// fill buffer
                            	msgBuffer[0] = rawbuffer[index + 1];
                            	msgBuffer[1] = rawbuffer[index + 2];
                            	msgBuffer[2] = rawbuffer[index + 3];
                                
                                index += 4;
                            }
                            else
                            {
                            	// fill buffer
                            	msgBuffer[0] = rawbuffer[index + 1];
                            			                               
                                index += 2;
                            }

                            // set the msg data
                            msg.setData(msgBuffer);
                            publishProgress(new NetEvent(msg));
                        }
                    	
                    	index = 0;
                    }
                    else
                        throw new Exception();
	    		}
        	}
	        catch(Exception e)
	        {
	        	// send message
	        	msg = new NetEvent();
    			msg.setEventID(NetEventType.TYPE_DISCON);
    			msg.setMsg("Disconnected from the vehicle");
	    		publishProgress(msg);
	        }
			
			return null;
		}
		
		@Override
		protected void onProgressUpdate(NetEvent... params)
		{
			// easier use of variable
			NetEvent event = params[0];
			
			// if we have a listener we pass the message to the listener
			if(mNetListener != null && event != null )
			{
				mNetListener.onNetEvent(event);
			}
		}
	}
}
